package tingshu.servlet.user;

import tingshu.service.UserService;
import tingshu.view_object.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 注册
 * @author houdaiqin
 * @date 2022/07/09 15:30
 **/
@WebServlet("/studio/user/register.do")
public class RegisterDoServlet extends HttpServlet {
    private final UserService userService=new UserService();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //从请求中获取用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if(username==null || username.equals("")){
            throw new ServletException("用户名为空");
        }
        if(password==null || password.equals("")){
            throw new ServletException("密码为空");
        }

        //将用户名和密码插入数据库中
        UserVO userVO=userService.register(username,password);

        //注册后直接进行登录（将用户对象放入 session中）
//        HttpSession session=req.getSession();
//        session.setAttribute("currentUser",userVO);

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/plain");
        PrintWriter printWriter=resp.getWriter();
        //printWriter.println("注册成功");
        resp.sendRedirect("/studio/user/login.html");
    }
}